const axios = require('axios');
const fs = require('fs');

const BASE_URL = 'http://localhost:3000/api';
const API_DOC_PATH = './api-docs.md';

// 存储API文档内容
let apiDocContent = `# 学生选课系统API文档

本文档详细描述了学生选课系统的所有API接口。

## 基本信息

- 基础URL: \`http://localhost:3000/api\`
- Content-Type: \`application/json\`
- 认证方式: JWT Token

## API端点

`;

// 记录API测试结果
function recordAPI(method, endpoint, description, auth, request = null, response = null, error = null) {
  apiDocContent += `### ${method} ${endpoint}\n\n`;
  apiDocContent += `**描述**: ${description}\n\n`;
  apiDocContent += `**需要认证**: ${auth ? '是' : '否'}\n\n`;

  if (request) {
    apiDocContent += `**请求示例**:\n\`\`\`json\n${JSON.stringify(request, null, 2)}\n\`\`\`\n\n`;
  }

  if (response) {
    apiDocContent += `**成功响应**:\n\`\`\`json\n${JSON.stringify(response, null, 2)}\n\`\`\`\n\n`;
  }

  if (error) {
    apiDocContent += `**错误响应**:\n\`\`\`\n${error}\n\`\`\`\n\n`;
  }

  apiDocContent += `---\n\n`;
}

async function testAPI() {
  console.log('开始API测试...');

  try {
    // 1. 测试服务器状态
    try {
      const response = await axios.get('http://localhost:3000/');
      console.log('✅ 服务器状态检查成功');
      recordAPI('GET', '/', '检查服务器状态', false, null, response.data);
    } catch (error) {
      console.log('❌ 服务器状态检查失败:', error.message);
      recordAPI('GET', '/', '检查服务器状态', false, null, null, error.message);
    }

    // 2. 测试数据库连接
    try {
      const response = await axios.get(`${BASE_URL}/test-db`);
      console.log('✅ 数据库连接测试成功');
      recordAPI('GET', '/test-db', '测试数据库连接', false, null, response.data);
    } catch (error) {
      console.log('❌ 数据库连接测试失败:', error.message);
      recordAPI('GET', '/test-db', '测试数据库连接', false, null, null, error.message);
    }

    // 3. 测试初始化管理员账户
    const adminData = {
      username: 'admin',
      password: 'admin123'
    };

    try {
      const response = await axios.post(`${BASE_URL}/auth/init-admin`, adminData);
      console.log('✅ 初始化管理员账户成功');
      recordAPI('POST', '/auth/init-admin', '初始化管理员账户', false, adminData, response.data);
    } catch (error) {
      console.log('❌ 初始化管理员账户失败:', error.message);
      recordAPI('POST', '/auth/init-admin', '初始化管理员账户', false, adminData, null, error.message);
    }

    // 4. 测试管理员登录
    try {
      const response = await axios.post(`${BASE_URL}/auth/login`, adminData);
      console.log('✅ 管理员登录成功');
      const adminToken = response.data.token;
      recordAPI('POST', '/auth/login', '用户登录', false, adminData, response.data);

      // 5. 使用管理员权限注册学生
      const studentData = {
        username: 'student1',
        password: 'password123',
        role: 'student',
        profile: {
          student_id: 'S12345',
          name: '测试学生',
          gender: '男',
          age: 20,
          class: '计算机1班',
          department: '计算机科学与技术',
          major: '软件工程'
        }
      };

      console.log('使用管理员Token:', adminToken);

      try {
        console.log('开始注册学生账户...');
        console.log('使用Token:', adminToken);
        const response = await axios.post(
          `${BASE_URL}/auth/register`,
          studentData,
          { 
            headers: { 
              'Authorization': `Bearer ${adminToken}`,
              'Content-Type': 'application/json'
            } 
          }
        );
        console.log('✅ 注册学生账户成功');
        recordAPI('POST', '/auth/register', '注册新用户', true, studentData, response.data);
      } catch (error) {
        console.log('❌ 注册学生账户失败:', error.message);
        recordAPI('POST', '/auth/register', '注册新用户', true, studentData, null, error.message);
      }

      // 6. 使用管理员权限注册教师
      const teacherData = {
        username: 'teacher1',
        password: 'password123',
        role: 'teacher',
        profile: {
          teacher_id: 'T12345',
          name: '测试教师',
          gender: '女',
          title: '副教授',
          department: '计算机科学与技术'
        }
      };

      try {
        const response = await axios.post(
          `${BASE_URL}/auth/register`,
          teacherData,
          { headers: { Authorization: `Bearer ${adminToken}` } }
        );
        console.log('✅ 注册教师账户成功');
        recordAPI('POST', '/auth/register', '注册新用户', true, teacherData, response.data);
      } catch (error) {
        console.log('❌ 注册教师账户失败:', error.message);
        recordAPI('POST', '/auth/register', '注册新用户', true, teacherData, null, error.message);
      }

    } catch (error) {
      console.log('❌ 管理员登录失败:', error.message);
      recordAPI('POST', '/auth/login', '用户登录', false, adminData, null, error.message);
    }

  } catch (error) {
    console.error('测试过程中发生错误:', error.message);
  } finally {
    // 保存API文档
    fs.writeFileSync(API_DOC_PATH, apiDocContent);
    console.log(`\nAPI测试完成，文档已生成: ${API_DOC_PATH}`);
  }
}

// 执行测试
testAPI();
